import { useEffect, useState, useCallback, useRef } from 'react';
import { List, Checkbox, Toast } from 'antd-mobile';
import service from './service';
import SimpleListView from '@inbiz/basic/SimpleListView';
import styles from './index.less';
import Breadcrumb from '../SyncComponents/WapBreadcrumb';
import { getParents } from './utils';
import SelectBar from './SelectBar';
import { getLowercase } from './utils/index';
import _ from 'lodash';
import { getMessage } from '@inbiz/react';

export default function DepartmentTab(props: any) {
  const listRef = useRef<any>();
  const [data, _data] = useState<any[]>([]);
  const [bread, _bread] = useState<any[]>([]);
  const [breadId, _breadId] = useState<number[]>([]);
  const { selected, selectedId, allSelected, multiple, onOk, onCancel, setSelected, tabKey } =
    props;
  let currentDepId = breadId[breadId.length - 1];

  const setBread = (breads: any[]) => {
    _bread(breads);
    _breadId(breads.map((v) => v.identityid));
  };

  const onRefresh = useCallback(
    (params: any) => {
      if(!currentDepId){
        return
      }
      service.getSubDepartmentList({ departId: currentDepId }).then((res) => {
        let arrData = res || [];
        _data(getLowercase(arrData, tabKey));
        // 每次刷新滚动到顶部
        listRef.current?.scroll(0, 0);
      });
    },
    [currentDepId],
  );

  const onRowSelectChange = useCallback(
    (row: any) => {
      return (checked: boolean) => {
        let index = selectedId.indexOf(row.key);
        if (checked) {
          if (index == -1) {
            let newSelected = [...selected, row];
            setSelected(newSelected);
          }
        } else {
          if (index > -1) {
            let newSelected = [...selected];
            newSelected.splice(index, 1);
            setSelected(newSelected);
          }
        }
        props.updateSelected && props.updateSelected(checked, row);
      };
    },
    [selectedId, selected],
  );

  const onClickRow = (e: any, row: any) => {
    let p = getParents(e.target, e.currentTarget.querySelector('.adm-list-item-content-extra'));
    if (p.length) {
      return;
    }
    service
      .getSubDepartmentList({
        departId: row?.identityid,
        id: row?.id,
      })
      .then((res) => {
        if (!_.isEmpty(res)) {
          _data(getLowercase(res, tabKey));
          let newBread = [...bread, row];
          setBread(newBread);
        } else {
          Toast.show({
            // 该部门下没有子部门
            content: getMessage(`WapMemberSelect.lang.noSubDepartment`),
          });
        }
      });
  };

  const onBreadItemClick = useCallback(
    (e, row, index) => {
      if (index == -1) {
        service.getTopDepartmentList().then((res) => {
          setBread([]);
          let arrData = res || [];
          _data(getLowercase(arrData, tabKey));
        });
      } else {
        service
          .getSubDepartmentList({
            departId: row?.identityid,
            id: row?.id,
          })
          .then((res) => {
            let newBreads = [...bread].slice(0, index + 1);
            setBread(newBreads);
            _data(getLowercase(res, tabKey) || []);
          });
      }
    },
    [bread],
  );

  useEffect(() => {
    service.getTopDepartmentList().then((res) => {
      let arrData = res || [];
      _data(getLowercase(arrData, tabKey));
    });
  }, []);

  return (
    <div className={styles.departmentTab}>
      {bread.length ? (
        <Breadcrumb
          nameKey={'name'}
          data={bread}
          onBreadItemClick={onBreadItemClick}
          showHome={true}
          onClickHome={() => {
            onBreadItemClick(null, null, -1);
          }}
          itemStyle={{ fontSize: 16 }}
        />
      ) : null}
      <SimpleListView
        style={{
          height: bread.length ? 'calc(100% - 45px)' : '100%',
        }}
        ref={listRef}
        onRefresh={onRefresh}
        renderRow={(row: any, index: number) => {
          return (
            <List.Item
              key={index}
              arrow={false}
              extra={
                <Checkbox
                  checked={selectedId.includes(row?.key)}
                  onChange={onRowSelectChange(row)}
                />
              }
              onClick={(e) => {
                onClickRow(e, row);
              }}
            >
              {row.name}
            </List.Item>
          );
        }}
        dataSource={data}
      />
      <SelectBar
        filterKey={tabKey}
        data={data}
        selectedId={selectedId}
        selected={selected}
        allSelected={allSelected}
        multiple={multiple}
        setSelected={setSelected}
        onOk={onOk}
        onCancel={onCancel}
      />
    </div>
  );
}
